package com.lyy.msgtool.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @ClassName DirectRabbitConfig
 * @Description TODO 直接交换机的配置
 * @Author louyangyi
 * @Date 2022/1/13 15:48
 **/
@Configuration
public class RabbitTypeConfig {

    @Value("${spring.rabbitmq.exchange.name:TestExchange}")
    private String exchange;
    @Value("${spring.rabbitmq.queue.name:TestQueue}")
    private String queue;
    @Value("${spring.rabbitmq.routeKey.name:TestRouteKey}")
    private String routeKey;
    @Value("${spring.rabbitmq.type:type}")
    private String type;

    //队列
    @Bean
    @ConditionalOnProperty(name = "spring.profiles.active",havingValue = "rabbitmq")
    public Queue Queue() {
        return new Queue(queue);
    }

    //交换机
    @Bean
    @ConditionalOnProperty(name = "spring.rabbitmq.type",havingValue = "fanout")
    FanoutExchange FanoutExchange() {
        return new FanoutExchange(exchange);
    }

    //交换机
    @Bean
    @ConditionalOnProperty(name = "spring.rabbitmq.type",havingValue = "topic")
    TopicExchange TopicExchange() {
        return new TopicExchange(exchange);
    }

    //绑定  将队列和交换机绑定
    @Bean
    @ConditionalOnProperty(name = "spring.profiles.active",havingValue = "rabbitmq")
    Binding binding() {
        if("fanout".equals(type)){
            return BindingBuilder.bind(Queue())
                    .to(FanoutExchange());
        }
        else if("topic".equals(type)){
            return BindingBuilder.bind(Queue())
                    .to(TopicExchange()).with(routeKey);
        }
        return BindingBuilder.bind(Queue())
                .to(FanoutExchange());
    }

    public String getExchange(){
        if(!StringUtils.hasText(exchange)){
            exchange="TestDirectExchange";
        }
        return exchange;
    }

    public String getQueue(){
        if(!StringUtils.hasText(queue)){
            queue="TestDirectQueue";
        }
        return queue;
    }

    public String getRouteKey(){
        if(!StringUtils.hasText(routeKey)){
            routeKey="TestRouteKey";
        }
        return routeKey;
    }
    public String getType(){
        if(!StringUtils.hasText(type)){
            type="fanout";
        }
        return type;
    }
}
